<template>
  <el-dialog title="修改主题酒店" :visible="dialogVisible" width="50%" :before-close="doClose">
    <el-form ref="hotelForm" label-position="right" label-width="120px" :model="hotel" :rules="hotelRules">
      <el-form-item prop="name" label="酒店名">
        <el-input v-model="hotel.name" />
      </el-form-item>
      <el-form-item prop="price" label="费用">
        <el-input v-model="hotel.price" />
      </el-form-item>
      <el-form-item label="主题">
        <el-select v-if="$store.getters.themeHotel.theme" v-model="hotel.hotelTheme.id" placeholder="请选择">
          <el-option
            v-for="item in $store.getters.themeHotel.theme"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="doClose">取 消</el-button>
      <el-button type="primary" @click="doUpdate">修 改</el-button>
    </span>
  </el-dialog>
</template>

<script>
import {
  validTravelName,
  validPrice
} from '@/utils/validate'
import { updateHotel } from '@/api/theme-hotel'
export default {
  props: {
    dialogVisible: {
      type: Boolean,
      required: true,
      default: false
    },
    hotel: {
      type: Object,
      required: true,
      default() {
        return {
          name: '',
          price: 0,
          hotelTheme: {
            id: 1
          }
        }
      }
    }
  }, data() {
    const validateTravelName = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入酒店名'))
      } else if (!validTravelName(value)) {
        callback(new Error('长度1-100'))
      } else {
        callback()
      }
    }
    const validatePrice = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输价格'))
      } else if (!validPrice(value)) {
        callback(new Error('这不是有效的两位小数'))
      } else {
        callback()
      }
    }
    return {
      hotelRules: {
        name: [{ required: true, trigger: 'blur', validator: validateTravelName }],
        price: [{ required: true, trigger: 'blur', validator: validatePrice }]
      }
    }
  },
  created() {

  },
  methods: {
    doUpdate() {
      this.$refs.hotelForm.validate(valid => {
        if (valid) {
          updateHotel(this.hotel).then(res => {
            this.$message.success(res.message)
            this.updated(res.data)
          })
        } else {
          this.$message.error('请检查表单')
        }
      })
    },
    updated(hotel) {
      this.$emit('updated', { hotel })
      this.doClose()
    },
    doClose() {
      this.$emit('close')
    }
  }
}
</script>

<style>

</style>
